package de.alt.rest.util;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.logging.Logger;

import de.alt.rest.constants.Constants;

/**
 * The Class WakeOnLan.
 */
public class WakeOnLan {

	/** The Constant log. */
	private static final Logger log = Logger.getLogger(NotifyMyAndroid.class.getName());

	/**
	 * Wake up.
	 * 
	 * @param ip
	 *            the ip
	 * @param mac
	 *            the mac
	 */
	public boolean wakeUp(String ip, String mac) {

		try {
			byte[] macBytes = getMacBytes(mac);
			byte[] bytes = new byte[6 + 16 * macBytes.length];
			for (int i = 0; i < 6; i++) {
				bytes[i] = (byte) 0xff;
			}
			for (int i = 6; i < bytes.length; i += macBytes.length) {
				System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
			}

			InetAddress address = InetAddress.getByName(ip);
			DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, Constants.WOL_PORT);
			DatagramSocket socket = new DatagramSocket();
			socket.send(packet);
			socket.close();
		} catch (Exception e) {
			log.warning("Failed to send Wake-on-LAN packet: " + e.getMessage());
			return false;
		}
		
		log.warning("Wake-on-LAN packet sent.");
		return true;
	}

	/**
	 * Gets the mac bytes.
	 * 
	 * @param macStr
	 *            the mac str
	 * @return the mac bytes
	 * @throws IllegalArgumentException
	 *             the illegal argument exception
	 */
	private byte[] getMacBytes(String macStr) throws IllegalArgumentException {
		byte[] bytes = new byte[6];
		String[] hex = macStr.split("(\\:|\\-)");
		if (hex.length != 6) {
			throw new IllegalArgumentException("Invalid MAC address.");
		}
		try {
			for (int i = 0; i < 6; i++) {
				bytes[i] = (byte) Integer.parseInt(hex[i], 16);
			}
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException("Invalid hex digit in MAC address.");
		}
		return bytes;
	}

}
